package com.itheima.web.filters;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.Result;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebFilter(urlPatterns = {"/system/*","/store/*"})
public class PermissionFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request=(HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        //1.获取访问路径
        String servletPath = request.getServletPath();// 得到/system/dept 或者/system/user ...
        String pathInfo = request.getPathInfo();//  得到标记 /findByPage /findAll /save /edit
        //2.如果标记是查询类的,那么直接放行,不进行权限验证
        if(pathInfo.substring(1).startsWith("find")||pathInfo.substring(1).startsWith("select")){
            chain.doFilter(req, resp);
            return;
        }
        //3.如果不是查询类的方法就要进行权限验证
        //3.1获取用户的权限列表
        List<String> curls = (List<String>)request.getSession().getAttribute("curls");
        //3.2如果权限列表不为空,就进行权限验证
        //3.2.1如果权限列表包含该方法,校验成功
        if(curls!=null&&curls.contains(servletPath+pathInfo)){
            chain.doFilter(req, resp);
        }else{
            //3.2.2如果权限列表不包含该方法,校验失败 响应权限不足的json结果
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(resp.getOutputStream(),new Result(false, MessageConstant.PERMISSION_FORBIDDEN));
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }
    public void destroy() {
    }

}
